using AutoMapper;
using Core.SimpleTemp.Application;
using Core.SimpleTemp.Application.ServiceApp.SysApp.FileApp;
using Core.SimpleTemp.Application.ZY;
using Core.SimpleTemp.Application.ZY.Dto;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// 作业许可证相关
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class ZY_licenseController : CoreApiController
    {
        private readonly ZY_licenseService _service;
        private readonly CoreDBContext _coreDBContext;
        /// <summary>
        /// ZY_license
        ///</summary>
        public ZY_licenseController(ZY_licenseService service, CoreDBContext coreDBContext)
        {
            _service = service;
            _coreDBContext = coreDBContext;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(ZY_licenseController) + "_" + nameof(ZY_licenseController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetList(PagingModel<ZY_licenseDto> pagingQueryModel)
        {
            IPageModel<ZY_licenseDto> result;
            result = await _service.GetList(pagingQueryModel);
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(ZY_licenseController) + "_" + nameof(ZY_licenseController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> SaveAsync(ZY_licenseDto dto)
        {
            dto.JobLicenseState = TickeState.Save.ToString();
            return await SaveDataAsync(dto);
        }


        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Submit")]
        [PermissionFilter(nameof(ZY_licenseController) + "_" + nameof(ZY_licenseController.Submit), AuthorizationConst.SAVE)]
        public async Task<IActionResult> Submit(ZY_licenseDto dto)
        {
            dto.JobLicenseState = TickeState.Submit.ToString();
            dto.ApplicationTime = DateTime.Now;
            return await SaveDataAsync(dto);
        }

        private async Task<IActionResult> SaveDataAsync(ZY_licenseDto dto)
        {
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                await _service.InsertAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                await _service.UpdateAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(ZY_licenseController) + "_" + nameof(ZY_licenseController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult> DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult> Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            var dto = Mapper.Map<ZY_licenseDto>(model);
            var files = await _coreDBContext.SysFile.Where(a => a.B_ID == id).ToListAsync();
            dto.Attachment = Mapper.Map<List<SysFileDto>>(files);

            //工作类型选中
            dto.CheckJobType_B = await _coreDBContext.ZY_Content.Where(a => a.PrimaryId == id && a.TypeCoce == DicType.TypeB).Select(a => a.ContentCode).ToListAsync();
            //危害意识选中
            dto.CheckHazardIdentification_C = await _coreDBContext.ZY_Content.Where(a => a.PrimaryId == id && a.TypeCoce == DicType.TypeC).Select(a => a.ContentCode).ToListAsync();
            //危害意识选中
            dto.CheckPersonalSecurityProtection_D = await _coreDBContext.ZY_Content.Where(a => a.PrimaryId == id && a.TypeCoce == DicType.TypeD).Select(a => a.ContentCode).ToListAsync();
            //工作前安全措施（工作区域准备）选中
            dto.CheckPreworkSafetyMeasures_E = await _coreDBContext.ZY_Content.Where(a => a.PrimaryId == id && a.TypeCoce == DicType.TypeE).Select(a => a.ContentCode).ToListAsync();
            //安全措施确认
            dto.CheckF_PreworkSafetyMeasures_F = await _coreDBContext.ZY_Content.Where(a => a.PrimaryId == id && a.TypeCoce == DicType.TypeF).Select(a => new CheckBoxModel()
            {
                Lable = a.ContentCode,
                Value = a.ContentOptions,
                Text = a.ContentOptionsText
            }).ToListAsync();

            //确认
            var confirmSignature = await _coreDBContext.ZY_ConfirmSignature.Where(a => a.PrimaryId == id).ToListAsync();
            var confirmSignatureDto = Mapper.Map<List<ZY_ConfirmSignatureDto>>(confirmSignature);
            dto.JobLicenceCheckList = confirmSignatureDto.Select(a => new LicenceCheckViewModel
            {
                DepartmentId = a.SignatureDept,
                DepartmentName = a.SignatureDeptText,
                UserId = a.SignatureUser,
                UserName = a.SignatureUserText,
                BusinessId = a.Id,
                SignaturePicID = a.SignaturePicID

            }).ToList();

            //审批
            var checkSignatures = await _coreDBContext.ZY_CheckSignature.Where(a => a.PrimaryId == id).ToListAsync();
            var dtoCheckSignatures = Mapper.Map<List<ZY_CheckSignatureDto>>(checkSignatures);
            dto.JobLicenceApproveList = dtoCheckSignatures.Select(a => new LicenceApproveViewModel
            {
                DutyName = a.DutyText,
                Id = a.DutyId,
                IsDutyOffice = a.IsDutyOffice,
                BusinessId = a.Id,
                SignaturePicID = a.SignaturePicID

            }).ToList();
            //查询出当前登录用户是否具有审批权限
            var dutyIdList = dto.JobLicenceApproveList.Select(a => a.Id);
            var userDepartmentDutys = await _coreDBContext.SysUserDepartmentDuty.Where(a => dutyIdList.Contains(a.SysDutyID)).ToListAsync();
            dto.JobLicenceApproveList.ForEach(a =>
            {
                var users = userDepartmentDutys.Where(udd => udd.SysDutyID == a.Id).Select(udd => udd.SysUserInforID);
                a.CanApprove = users.Any(u => u == UserIdentity.Id);
            });
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);
            return this.JsonSuccess(dto);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(ZY_licenseController) + "_" + nameof(ZY_licenseController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult> Export(PagingModel<ZY_licenseDto> pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
        #endregion


        /// <summary>
        /// 申请人签字
        /// </summary>
        /// <param name="signViewModel"></param>
        /// <returns></returns>
        [HttpPost("ApplicantConfirmation")]
        public async Task<ActionResult> ApplicantConfirmation(SignViewModel signViewModel)
        {
            var license = await _coreDBContext.ZY_license.SingleAsync(a => a.Id == signViewModel.BusinessId);
            if (signViewModel.IsCancel)
            {
                if (license.JobLicenseState != TickeState.ApplicantConfirmation.ToString())
                    return this.JsonFaild("当前状态下不能进行取消操作");
                license.ApplicantConfirmation = signViewModel.SignFileId = null;
                license.ApplicantConfirmationDate = signViewModel.SignDate = null;
                license.JobLicenseState = TickeState.Submit.ToString();
            }
            else
            {
                if (license.JobLicenseState != TickeState.Submit.ToString())
                    return this.JsonFaild("签字异常：只有在票据状态为提交时才能进行申请人签字操作");
                var userInfo = _coreDBContext.SysUserInfor.SingleOrDefault(a => a.SysUserID == UserIdentity.Id);
                license.ApplicantConfirmation = signViewModel.SignFileId = userInfo.SignID;
                license.ApplicantConfirmationDate = signViewModel.SignDate = DateTime.Now;
                license.JobLicenseState = TickeState.ApplicantConfirmation.ToString();
            }
            await _coreDBContext.SaveChangesAsync();
            return this.JsonSuccess(signViewModel);

        }


        /// <summary>
        /// 相关单位签字确认（确认人签字）
        /// </summary>
        /// <param name="signViewModel"></param>
        /// <returns></returns>
        [HttpPost("correlationUnitSign")]
        public async Task<ActionResult> CorrelationUnitSign(SignViewModel signViewModel)
        {
            var confirmSignature = await _coreDBContext.ZY_ConfirmSignature.SingleAsync(a => a.Id == signViewModel.BusinessId);
            var license = await _coreDBContext.ZY_license.SingleAsync(a => a.Id == confirmSignature.PrimaryId);
            if (license.JobLicenseState != TickeState.ApplicantConfirmation.ToString())
                return this.JsonFaild("签字异常：只有在票据状态为提交时才能进行申请人签字操作");
            if (signViewModel.IsCancel)
            {
                confirmSignature.SignaturePicID = signViewModel.SignFileId = null;
                confirmSignature.SignatureTime = signViewModel.SignDate = null;
                license.JobLicenseState = TickeState.ApplicantConfirmation.ToString();
            }
            else
            {
                var userInfo = _coreDBContext.SysUserInfor.SingleOrDefault(a => a.SysUserID == UserIdentity.Id);
                confirmSignature.SignaturePicID = signViewModel.SignFileId = userInfo.SignID;
                confirmSignature.SignatureTime = signViewModel.SignDate = DateTime.Now;
                //所有均确认，状态设置为SignatureOfConfirmer
                var confirmSignatures = _coreDBContext.ZY_ConfirmSignature.Where(a => a.PrimaryId == license.Id && a.SignaturePicID == null && a.SignatureTime == null && a.Id != confirmSignature.Id);
                if (!confirmSignatures.Any())
                    license.JobLicenseState = TickeState.SignatureOfConfirmer.ToString();
            }
            await _coreDBContext.SaveChangesAsync();
            return this.JsonSuccess(signViewModel);
        }


        /// <summary>
        /// 批准人签字
        /// </summary>
        /// <param name="signViewModel"></param>
        /// <returns></returns>
        [HttpPost("ApproveSign")]
        public async Task<ActionResult> ApproveSign(SignViewModel signViewModel)
        {
            //申请人
            var checkSignature = await _coreDBContext.ZY_CheckSignature.SingleAsync(a => a.Id == signViewModel.BusinessId);
            var license = await _coreDBContext.ZY_license.SingleAsync(a => a.Id == checkSignature.PrimaryId);
            if (license.JobLicenseState != TickeState.SignatureOfConfirmer.ToString())
                return this.JsonFaild("签字异常：只有确认人确认后才能进行审批签字操作");
            if (signViewModel.IsCancel)
            {
                checkSignature.SignaturePicID = signViewModel.SignFileId = null;
                checkSignature.SignatureTime = signViewModel.SignDate = null;
                license.JobLicenseState = TickeState.SignatureOfConfirmer.ToString();
            }
            else
            {
                var userInfo = _coreDBContext.SysUserInfor.SingleOrDefault(a => a.SysUserID == UserIdentity.Id);
                checkSignature.SignaturePicID = signViewModel.SignFileId = userInfo.SignID;
                checkSignature.SignatureTime = signViewModel.SignDate = DateTime.Now;
                //所有均确认，状态设置为SignatureOfConfirmer
                var confirmSignatures = _coreDBContext.ZY_CheckSignature.Where(a => a.PrimaryId == license.Id && a.SignaturePicID == null && a.SignatureTime == null && a.Id != checkSignature.Id);
                if (!confirmSignatures.Any())
                    license.JobLicenseState = TickeState.SignatureOfApprover.ToString();
            }
            await _coreDBContext.SaveChangesAsync();
            return this.JsonSuccess(signViewModel);

        }
    }
}
